//
//  MMLocationManager.m
//  first
//
//  Created by 毕小强 on 16/12/7.
//  Copyright © 2016年 毕小强. All rights reserved.
//

#import "MMLocationManager.h"

@implementation MMLocationManager
+(instancetype)sharedManager{
    static MMLocationManager*manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MMLocationManager alloc]init];
    });
    return manager;
}
-(instancetype)init{
    if (self = [super init]) {
        self.minSpeed = 3;
        self.minFilter = 50;
        self.minInteval = 10;
        
        self.delegate = self;
        self.distanceFilter = self.minFilter;
        self.desiredAccuracy = kCLLocationAccuracyBest;
    }
    return self;
}
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation*location = locations[0];
    NSLog(@"%@",location);
    //根据实际情况来调整触发范围
    [self adjustDistanceFilter:location];
    
    //上传数据
    [self uploadLocation:location];
}
/**
 *  规则: 如果速度小于minSpeed m/s 则把触发范围设定为50m
 *  否则将触发范围设定为minSpeed*minInteval
 *  此时若速度变化超过10% 则更新当前的触发范围(这里限制是因为不能不停的设置distanceFilter,
 *  否则uploadLocation会不停被触发)
 */
-(void)adjustDistanceFilter:(CLLocation*)location{
    if ( location.speed < self.minSpeed )
    {
        if ( fabs(self.distanceFilter-self.minFilter) > 0.1f )
        {
            self.distanceFilter = self.minFilter;
        }
    }
    else
    {
        float lastSpeed = self.distanceFilter/self.minInteval;
        
        if ( (fabs(lastSpeed-location.speed)/lastSpeed > 0.1f) || (lastSpeed < 0) )
        {
            float newSpeed  = (int)(location.speed+0.5f);
            float newFilter = newSpeed*self.minInteval;
            
            self.distanceFilter = newFilter;
        }
    }
}
-(void)uploadLocation:(CLLocation*)location{
    NSDate*currentDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss SS"];
    NSString *dateStr = [dateFormatter stringFromDate:currentDate];
    
    NSLog(@"纬度=========%f 经度===========%f",location.coordinate.latitude,location.coordinate.longitude);
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSArray *arr = [userDefaults objectForKey:@"UserDefaultLocation"];
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithDouble:location.coordinate.latitude],@"latitude",[NSNumber numberWithDouble:location.coordinate.longitude],@"longitude",dateStr,@"time", nil];
    if (arr) {
        NSMutableArray *mArr = [NSMutableArray arrayWithArray:arr];
        [mArr addObject:dic];
        arr = mArr;
    }else{
        arr = [NSArray arrayWithObject:dic];
    }
    //NSLog(@"%@",arr);
    [userDefaults setObject:arr forKey:@"UserDefaultLocation"];
    [userDefaults synchronize];
}
@end
